package cn.t.facade.device;


import cn.t.constants.CommonConstants;
import cn.t.constants.ResponseError;
import cn.t.converter.device.DeviceDataDTOConverter;
import cn.t.core.exception.BizException;
import cn.t.core.facade.FacadeImpl;
import cn.t.dto.device.DeviceDataDTO;
import cn.t.dto.device.DeviceUpstreamDO;
import cn.t.dto.device.vo.OpenCloseDTO;
import cn.t.enums.ActionTypeEnum;
import cn.t.enums.OptionTypeEnum;
import cn.t.model.device.DeviceDataDO;
import cn.t.service.device.DeviceDataService;
import cn.t.utils.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 设备盘点数据表(DeviceData)服务编排
 *
 * @author t
 * @since 2024-05-24 10:19:33
 */
@Slf4j
@Service
@AllArgsConstructor
public class DeviceDataFacade extends FacadeImpl<DeviceDataDTO, DeviceDataDO, DeviceDataDTOConverter, DeviceDataService> {
    @Autowired
    private ObjectMapper objectMapper;

    public void addInfo(OpenCloseDTO openCloseWeightVO) {
        DeviceDataDO deviceDataDO = converter.vo2Do(openCloseWeightVO);
        try {
            deviceDataDO.setDeviceData(objectMapper.writeValueAsString(new DeviceUpstreamDO(openCloseWeightVO.getScale())));
        } catch (Exception e) {
            log.error("DeviceData.add.setDeviceData error:{}", e.getMessage());
            throw new BizException(ResponseError.DATA_ERR, ResponseError.DATA_ERR.getName());
        }
        deviceDataDO.setBusinessType(openCloseWeightVO.getOptionTypeEnum().getCode());
        deviceDataDO.setRecordAt(DateUtil.dateByStr(openCloseWeightVO.getRecordAt()));
        deviceDataDO.setAction(openCloseWeightVO.getActionTypeEnum().getCode());
        deviceDataDO.setCreator(openCloseWeightVO.getOperatorInfo());
        deviceDataDO.setModifier(openCloseWeightVO.getOperatorInfo());
        service.add(deviceDataDO);
    }
   public List<DeviceDataDO>  findDataByOrderSn(OpenCloseDTO model, OptionTypeEnum optionTypeEnum, Date recordAt) {
       DeviceDataDO deviceDataDO = new DeviceDataDO();
       deviceDataDO.setDeviceId(model.getDeviceId());
       deviceDataDO.setOrderSn(model.getOrderSn());
       if (model.getActionTypeEnum().equals(ActionTypeEnum.close)){
           deviceDataDO.setRequestId(model.getRequestId());
       }
       if (optionTypeEnum!=null){
           deviceDataDO.setBusinessType(optionTypeEnum.getCode());
       }

       deviceDataDO.setRecordAt(recordAt);
       return service.findByModel(deviceDataDO, CommonConstants.ZERO, Integer.MAX_VALUE, " record_at ", " asc");
   }

}

